/*
 * Copyright 2010 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.mnit.basis.swt.timer;

import org.eclipse.swt.widgets.Display;

import de.mnit.basis.daten.struktur.container.Engpass;
import de.mnit.basis.fehler.Fehler;
import de.mnit.basis.fehler.Warnung;
import de.mnit.basis.swt.dialog.SWT_Fehler;

/**
 * @author Michael Nitsche
 * 25.06.2007	Erstellt
 *
 * TODO Mit den Basis-Timer-Komponenten vereinen
 */
public abstract class A_SWT_Timer implements S_SWT_Timer {

	private Display display;
	private int ms;
	private Runnable run;
	private Engpass<Boolean> pause=Engpass.neu();


	public A_SWT_Timer(int start_ms) {
		this.pause.s(false);
		this.ms=start_ms;
	}


	public void start(Display display) {
		Fehler.objekt.wenn_Null(display);
		this.display=display;
		this.run=new Runnable() {
			public void run() {
				try {
					if(pause.g())
						return;
					befehl();
					iStart();
				}
				catch(Throwable t) {
					Fehler.zeig(t); //Kein SWT-Fehler, sonst wird man u.U. mit dem Klicken nicht mehr fertig!
				}
			}
		};
		iStart();
	}

	public void start() {
		Fehler.objekt.wenn_Null(this.run, this.display);
		this.pause.s(false);
		iStart();
	}

	public void stop() {
		this.pause.s(true);
	}

	public void sZeit(int ms) {
		Warnung.wennAusserhalb(50, 10000, ms);
		this.ms=ms;
	}

	public abstract void befehl();


	private void iStart() {
		try {
			this.display.timerExec(this.ms, run);
		}
		catch(Exception e) {
			Fehler.zeig(e, false);
			SWT_Fehler.zeig(e, "Timer-Thread konnte nicht gestartet werden!", false);
		}
	}
}
